package com.small.nacos.core.cluster;

import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.small.nacos.sys.env.EnvUtil;
import com.small.nacos.sys.utils.IPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author zhoujin
 * @Date 2022/11/5 10:36
 */
public class MemberUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(MemberUtil.class);

    public static Member singleParse(String member) {
        // Nacos default port is 8848
        int defaultPort = 8848;
        // Set the default Raft port information for securit

        String address = member;
        int port = defaultPort;
        String[] info = IPUtil.splitIPPortStr(address);
        if (info.length > 1) {
            address = info[0];
            port = Integer.parseInt(info[1]);
        }

        Member target = Member.builder().ip(address).port(port).state(NodeState.UP).build();

        return target;
    }

    public static List<String> simpleMembers(Collection<Member> members) {
        return members.stream().map(Member::getAddress).sorted()
                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
    }


    public static Set<Member> selectTargetMembers(Collection<Member> members, Predicate<Member> filter) {
        return members.stream().filter(filter).collect(Collectors.toSet());
    }

    public static Collection<Member> readServerConf(Collection<String> members) {
        Set<Member> nodes = new HashSet<>();

        for (String member : members) {
            Member target = singleParse(member);
            nodes.add(target);
        }
        return nodes;
    }

    public static void syncToFile(Collection<Member> members) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("#").append(LocalDateTime.now()).append(StringUtils.LF);
            for (String member : simpleMembers(members)) {
                builder.append(member).append(StringUtils.LF);
            }
            EnvUtil.writeClusterConf(builder.toString());
        } catch (Throwable ex) {
            LOGGER.error("cluster member node persistence failed : {}", ExceptionUtil.getAllExceptionMsg(ex));
        }
    }
}
